'use strict';

const BaseService = require('./base');
const modelName = 'Address';
class AddressService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }
  async create(data) {
    delete data.id
    const res = await this.ctx.model[this.modelName].create({
      ...data,
    });
    try {
      await this.setDefault(res.id, data.member_user_id)
    } catch (e) {
      await this.deleteById(res.id);
    }
    return res
  }
  // 获取用户的所有地址
  async getUserAddresses(userId) {
    const { ctx } = this;
    return await ctx.model.Address.findAll({
      where: { member_user_id: userId },
      order: [['is_default', 'DESC'], ['create_time', 'DESC']]
    });
  }

  // 设置默认地址
  async setDefault(id, userId) {
    const { ctx } = this;
    const transaction = await ctx.model.transaction();
    try {
      // 先将该用户所有地址设为非默认
      await ctx.model.Address.update(
        { is_default: false },
        { 
          where: { member_user_id: userId },
          transaction
        }
      );
      
      // 再将指定地址设为默认
      await ctx.model.Address.update(
        { is_default: true },
        { 
          where: { id, member_user_id: userId },
          transaction
        }
      );
      
      await transaction.commit();
      return true;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  async getDefault(userId) {
    const { ctx } = this;
    return await ctx.model.Address.findOne({
      where: { member_user_id: userId, is_default: true },
    })
  }
}

module.exports = AddressService;
